package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.mywork.WorkUIKit;
import com.shwread.android.qysw10000192.R;
import com.shwread.android.ui.dialog.ContactCallSelectDialog;
import com.shwread.android.ui.widget.CircleImageView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import logic.bean.GroupBean;
import logic.dao.GroupDao;
import logic.util.Util;
import logic.util.Utils;
/*
* 查找审批人
*
* */

public class SearchApproverActivity extends
        BaseBusinessActivity
        implements
        View.OnClickListener,
        AdapterView.OnItemClickListener
{
    private Context mContext;
    private static boolean          TextIsChange   = false;

    private TextView tvNoContacts;
    private ListView lvContacts;
    private RelativeLayout rlayContactsSearchBlackBg, rlayContactsSearchResult;
    private Button btnSearch, btnClear;
    private AutoCompleteTextView autotvContactsName;

    private List<AddressBookInfo> contactResults = new ArrayList<AddressBookInfo>();
    private AddressBookInfoDao addressBookInfoDao;
    private GroupDao groupDao;
    public String                   condition;

    // 隐藏系统输入法
    InputMethodManager mInputMethodManager;

    private ContactAdapter          contactAdapter;

    private ContactCallSelectDialog selectNum;

    public static final String action = "jason.broadcast.action";

    @Override
    public Handler getUIHandler() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_approver);
        mContext = this;
        addressBookInfoDao = AddressBookInfoDao.getInstance(mContext);
        groupDao = GroupDao.getInstance(mContext);
        initViews();
        setListeners();
    }

    private void setListeners() {
        btnClear.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        autotvContactsName.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s))
                {
                    TextIsChange = false;
                    btnClear.setVisibility(View.GONE);
                    btnSearch.setText("取消");
                }
                else
                {
                    TextIsChange = true;
                    btnClear.setVisibility(View.VISIBLE);
                    btnSearch.setText("搜索");
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initViews() {
        btnClear = (Button) findViewById(R.id.book_read_search_searchbox_clear_btn);
        btnSearch = (Button) findViewById(R.id.book_read_search_search_btn);
        autotvContactsName = (AutoCompleteTextView) findViewById(R.id.book_read_search_searchbox_edit_autotv);
        autotvContactsName.setHint("联系人姓名");

        tvNoContacts = (TextView) findViewById(R.id.book_search_result_no_books_tv);
        tvNoContacts.setText("未搜到相关结果");
        lvContacts = (ListView) findViewById(R.id.book_search_result_books_lv);
        rlayContactsSearchBlackBg = (RelativeLayout) findViewById(R.id.book_search_black_rlay);
        rlayContactsSearchResult = (RelativeLayout) findViewById(R.id.book_search_result_rlay);
        rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Util.showInputMethodManager(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_read_search_search_btn:
                if (TextIsChange)
                {
                    Util.hideInputMethodManager(this, autotvContactsName);
                    searchContacts();
                }
                else
                {// 取消搜索
                    onBackPressed();
                    // 隐藏系统输入法
                    Util.hideInputMethodManager(this, autotvContactsName);

                    rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
                    rlayContactsSearchResult.setVisibility(View.GONE);
                    tvNoContacts.setVisibility(View.GONE);
                    lvContacts.setVisibility(View.GONE);
                }
                break;
            case R.id.book_read_search_searchbox_clear_btn:
                autotvContactsName.setText("");
                rlayContactsSearchBlackBg.setVisibility(View.VISIBLE);
                rlayContactsSearchResult.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void searchContacts() {
        condition = autotvContactsName.getText().toString().trim();
        if (Util.isEmpty(condition))
        {
            Util.showToast(mContext, "搜索内容不能为空哦");
        }
        else
        {
            contactResults = addressBookInfoDao.search(condition);
            if (addressBookInfoDao.searchByPhone(condition) != null) {
                contactResults = addressBookInfoDao.searchByPhone(condition);
                if (addressBookInfoDao.search(condition) != null)
                    contactResults.addAll(addressBookInfoDao.search(condition));
            }
        }
        if (contactResults != null)
        {
            //显示搜索结果
            rlayContactsSearchBlackBg.setVisibility(View.GONE);
            rlayContactsSearchResult.setVisibility(View.VISIBLE);
            lvContacts.setVisibility(View.VISIBLE);
            tvNoContacts.setVisibility(View.GONE);
            TextIsChange = false;
            btnSearch.setText("取消");
            contactAdapter = new ContactAdapter();
            lvContacts.setAdapter(contactAdapter);
        }
        else
        {
            rlayContactsSearchBlackBg.setVisibility(View.GONE);
            rlayContactsSearchResult.setVisibility(View.VISIBLE);
            tvNoContacts.setVisibility(View.VISIBLE);
            lvContacts.setVisibility(View.GONE);
        }
    }

    class ContactAdapter
            extends
            BaseAdapter
    {
        ViewHolder holder;

        @Override
        public int getCount() {
            return contactResults.size();
        }

        @Override
        public Object getItem(int position) {
            return contactResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(SearchApproverActivity.this).inflate(R.layout.search_approver_item, null);
                holder.contactsHeadImg = (CircleImageView) convertView.findViewById(R.id.iv_chat_head_img);
                holder.contactsHeader = (ImageView) convertView.findViewById(R.id.iv_chat_contact_icon_header);

                holder.contactsName = (TextView) convertView.findViewById(R.id.tv_chat_contact_name);
                holder.rlItem = (RelativeLayout) convertView.findViewById(R.id.rl_contact_item);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            GroupBean group = groupDao.getById(contactResults.get(position).getGroupId());
            final String groupName = group.getName();

            if (Utils.isNotEmpty(contactResults.get(position).getUserHead()))
            {
                //			ImageUtil.loadLocalUrl(contactItem.getUserHead(), contactsHeadImg);
                Picasso.with(mContext).load(contactResults.get(position).getUserHead()).into(holder.contactsHeadImg);
            }
            else
            {
                Picasso.with(mContext).load(R.drawable.chat_head_img).into(holder.contactsHeadImg);
                //			contactsHeadImg.setBackgroundResource(R.drawable.chat_head_img);
            }
            if (contactResults.get(position).getGroupPosition() == 1)
            {
                Picasso.with(mContext).load(R.drawable.chat_contract_icon_header).into(holder.contactsHeader);
                //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_header);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            }
            else if (contactResults.get(position).getGroupPosition() == 2)
            {
                Picasso.with(mContext).load(R.drawable.chat_contract_icon_deputy_header).into(holder.contactsHeader);
                //			contactsHeader.setBackgroundResource(R.drawable.chat_contract_icon_deputy_header);
                holder.contactsHeader.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.contactsHeader.setVisibility(View.GONE);
            }
            holder.contactsName.setText(contactResults.get(position).getContactName());
            holder.rlItem.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {
                    if (WorkUIKit.getUserId().equals(contactResults.get(position).getUserId())){
                        Log.e("fff","fffff");
                        Toast.makeText(SearchApproverActivity.this,"不能选自己为审批人，请重新选择",Toast.LENGTH_SHORT).show();
                    }else {
                        Intent intent = new Intent(action);
                        intent.putExtra("data", holder.contactsName.getText());
//                        intent.putExtra("jb",contactResults.get(position).getUserPositionMark());
                        intent.putExtra("userId", contactResults.get(position).getUserId());
                        intent.putExtra("userHead", contactResults.get(position).getUserHead());

                        sendBroadcast(intent);

                    }

//                    //EventBus发送数据
//                    EventBus.getDefault().post(new BusinessEvent(Integer.parseInt(contactResults.get(position).getUserId()),holder.contactsName.getText().toString()));

                    finish();


                }
            });



            return convertView;
        }

    }

    private class ViewHolder
    {
        CircleImageView contactsHeadImg;
        ImageView       contactsHeader;
        TextView        contactsName;
        RelativeLayout  rlItem;
    }



}
